<template>
    <!-- <el-dialog :title="title" :visible.sync="dialogVisible" width="1100px" append-to-body> -->
    <div class="layout-route purchase-detail">
        <div class="header">
            <el-button icon="el-icon-arrow-left" @click="cancel">返回</el-button> <span class="header-title">{{ title }}</span>
        </div>

        <div class="card">
            <el-form ref="form" :model="model" :rules="rules" label-width="90px" label-suffix=":" class="form-wrap-class">
                <el-row type="flex">
                    <el-col>
                        <el-form-item label="采购类型" prop="warehouse">
                            <el-select v-model="purchaseType" placeholder="请选择采购类型" clearable style="width: 240px" disabled>
                                <el-option label="线下直采" :value="1"></el-option>
                                <el-option label="1688采购" :value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col :span="12">
                        <el-form-item label="供应商姓名" prop="supply_id" style="width: 100%">
                            <SelectPage
                                v-model="model.supply_id"
                                placeholder="请选择供应商"
                                :url="$api.supply.getSupplyList"
                                show_field="supply_name"
                                query_field="supply_name"
                                query_field2="spu"
                                filterable
                                clearable
                                popper-class="custom-select"
                                style="width: 240px"
                            ></SelectPage>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="采购人员" prop="operater_id" style="width: 100%">
                            <!-- <el-select v-model="model.operater_id" placeholder="请选择采购人员" style="width: 240px">
                                <el-option v-for="dict in dict.purchaserList" :key="dict.operater_id" :label="dict.username" :value="dict.operater_id"></el-option>
                            </el-select> -->
                            <SelectPage
                                v-model="model.operater_id"
                                placeholder="请选择采购人员"
                                :url="$api.purchase.getPurchaserList"
                                show_field="username"
                                show_id="operater_id"
                                query_field="keyword"
                                filterable
                                clearable
                                popper-class="custom-select"
                                style="width: 240px"
                            ></SelectPage>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex">
                    <el-col :span="12">
                        <el-form-item label="运费均摊" prop="track_fee_type">
                            <el-select v-model="model.track_fee_type" placeholder="请选择运费均摊" style="width: 240px">
                                <el-option v-for="dict in dict.freightList" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="收货仓库" prop="warehouse" style="width: 100%">
                            <el-select v-model="model.warehouse" placeholder="" style="width: 240px">
                                <el-option v-for="item in dict.warehouseList" :key="item.id" :label="item.name" :value="item.name"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" class="mb8">
                    <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">批量添加商品</el-button>
                    <el-button type="primary" icon="el-icon-plus" @click="showSellerDialog">添加商品</el-button>
                    <el-button type="warning" icon="el-icon-delete" @click="batchDelete">批量移除</el-button>
                </el-row>
                <!-- <el-form-item label="" prop="purchase_detail" class="full"> -->
                <el-table :data="model.purchase_detail" border script style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="图片" prop="seller_sku">
                        <template slot-scope="scope">
                            <ImageUploadImg v-model="scope.row.image_url" :readOnly="true"></ImageUploadImg>
                        </template>
                    </el-table-column>
                    <el-table-column label="商品sku" prop="seller_sku"></el-table-column>

                    <el-table-column label="数量" prop="purchase_quantity">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.purchase_quantity" placeholder="请输入数量" style="width: 100%" @change="getTotal(scope.row, scope.$index)"></el-input>
                        </template>            
                    </el-table-column>
                    <el-table-column label="成本价" prop="purchase_price">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.purchase_price" placeholder="请输入成本价" style="width: 100%" @change="getTotal(scope.row, scope.$index)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="小计" prop="purchase_cost">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.purchase_cost" placeholder="请输入小计" style="width: 100%"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remark">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.remark" placeholder="请填写备注" style="width: 100%"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                        <template slot-scope="scope">
                            <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- </el-form-item> -->
                <el-row type="flex">
                    <el-col :span="8">
                        <el-form-item label="商品种类" prop="sku_nums" style="width: 100%">
                            <span>{{ model.sku_nums }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="商品数量" prop="purchase_quantity" style="width: 100%">
                            <span>x {{ model.purchase_quantity }}</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="采购总额" prop="purchase_cost" style="width: 100%">
                            <span style="font-size: 18px; color: red">{{ model.purchase_cost }}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="采购备注" prop="seller_sku" class="full">
                            <el-input v-model="model.remark" placeholder="采购备注" style="width: 100%">
                                <div style="display: flex; align-items: center" slot="append">
                                    <div class="color-item" :style="{ backgroundColor: remarkColor }"></div>
                                    <el-select v-model="model.remark_color" slot="append" placeholder="">
                                        <el-option v-for="item in dict.colorList" :key="item.value" :value="item.value">
                                            <div :style="{ backgroundColor: item.label, 'margin-top': '7px' }" class="color-item"></div>
                                        </el-option>
                                    </el-select>
                                </div>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="purchase-footer">
            <el-button type="primary" :loading="save" :disabled="save" @click="submit('save')">保存</el-button>
            <el-button type="primary" :loading="save" :disabled="save" @click="submit('send')">保存，并提交审核</el-button>
            <el-button type="primary" :loading="save" :disabled="save" @click="submit('pass')">保存，并通过审核</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>

        <SpuListDialog v-model="sellerDialog.visible" :params="sellerDialog.data" @selectRow="selectSeller"></SpuListDialog>
        <el-dialog :visible.sync="addVisible" title="批量添加商品" width="600" append-to-body v-loading="save">
            <el-row type="flex">
                <span>导入内容：</span>
                <el-radio-group v-model="addType">
                    <el-radio :label="1">SKU</el-radio>
                    <el-radio :label="2">SKU+数量</el-radio>
                </el-radio-group>
            </el-row>
            <el-input type="textarea" v-model="addData" :rows="8" placeholder="每行一个SKU(从Excel直接粘贴)"></el-input>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" :loading="save" :disabled="save" @click="batchAddSeller">导入</el-button>
                <el-button @click="closeAddDialog">关闭</el-button>
            </div>
        </el-dialog>
    </div>
    <!-- </el-dialog> -->
</template>

<script>
import { getWarehouseList } from '@/api/warehouse'
import { editPurchaseDown, getPurchaseDown, addPurchaseDown, getPurchaser, getWarehouseSkuImport } from '@/api/purchase'
import SpuListDialog from './SpuListDialog.vue'
export default {
    name: 'DetailDialog',
    components: { SpuListDialog },
    props: {
        value: {
            type: Boolean,
            default: false,
            required: true,
        },
        params: {
            type: Object,
            default: () => {},
        },
        type: {
            type: String,
            default: '',
        },
    },
    data() {
        return {
            addVisible: false,
            addType: 1,
            addData: '',
            purchaseType: 1,
            model: {
                is_pass: 1, // 1 , 0
                is_send: 1, // 1 , 0
                purchase_detail: [],
                operater_id: undefined,
                track_fee_type: undefined,
                warehouse: undefined,
                sku_nums: 0,
                purchase_cost: 0,
                purchase_quantity: 0,
                remark: '',
                remark_color: 2,
            },
            rules: {},
            dict: {
                purchaserList: [],
                colorList: [
                    { label: '#c03639', value: 1 },
                    { label: '#30b08f', value: 2 },
                ],
                freightList: [
                    { label: '按数量', value: 1 },
                    { label: '按金额', value: 2 },
                    { label: '按质量', value: 3 },
                    { label: '不均摊', value: 4 },
                ],
            },
            save: false,
            sellerDialog: {
                visible: false,
                data: {},
            },
            multipleSelection: []
        }
    },
    watch: {
        'model.purchase_detail': {
            handler(val) {
                this.model.purchase_cost = val.reduce((pre, cur) => pre + parseFloat(cur?.purchase_cost || 0), 0).toFixed(2)
                this.model.purchase_quantity = val.reduce((pre, cur) => pre + parseInt(cur?.purchase_quantity || 0), 0)
                this.model.sku_nums = val.length
            },
            deep: true,
        },
    },
    computed: {
        remarkColor() {
            return this.dict.colorList.find(item => item.value == this.model.remark_color)?.label
        },
        title() {
            const map = {
                add: '创建采购单',
                edit: '编辑采购单',
                confirm: '确认采购',
            }
            return map[this.type]
        },
        isConfirm() {
            return this.type === 'confirm'
        },
        isAdd() {
            return this.type === 'add'
        },
        dialogVisible: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val)
            },
        },
    },
    async mounted() {
        try {
            const [purchaserData, warehouseData] = await Promise.all([getPurchaser(), getWarehouseList()])

            this.dict.purchaserList = Array.isArray(purchaserData.data) ? purchaserData.data : [purchaserData.data] ?? []
            this.dict.warehouseList = warehouseData?.data?.list ?? []
        } catch (error) {
            console.log(error)
        }
        if (this.isAdd) {
            return
        }
        this.model.purchase_number = this.params.purchase_number
        if(this.model.purchase_number) {
            this.getDetail()
        }
    },
    methods: {
        getTotal(row, index) {
            row.purchase_cost = parseFloat(row.purchase_price) * parseInt(row.purchase_quantity).toFixed(2)
            this.model.purchase_detail.splice(index, 1, row)
        },
        openAddDialog() {
            this.addVisible = true
        },
        closeAddDialog() {
            this.addVisible = false
            this.addData = ''
            this.addType = 1
        },
        cancel() {
            // this.dialogVisible = false
            this.$emit('cancel')
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        batchAddSeller() {
            if(this.addData.length == 0) {
                return this.$message.warning('请输入要添加的数据')
            }
            
            
            //   批量添加
            const skuList = this.addData.split('\n').filter(item => item.trim() !== '')
            // const params = { sku_list: skuList, type: this.addType, purchase_number: this.model.purchase_number }
            // 修改连接符为 空格
            const params = {
                in_stores: skuList.map(item=>{
                    const list = item.split(' ').filter(pre=>pre.trim() !== '')
                    return {
                        seller_sku: list[0],
                        in_stores_quantity: list[1]??0
                    }
                })
            }
            getWarehouseSkuImport(params).then(res=>{
                res.data.map(item => {
                    this.addItem(item)
                })
            })
            // ... 调用接口
            this.addVisible = false
            this.msgSuccess('新增成功')
            
        },
        batchDelete() {
            if(this.multipleSelection.length == 0) {
                return this.$message.warning('请先选择要删除的数据')
            }
            this.$confirm('是否确认删除?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                   this.multipleSelection.forEach(row=>{
                        this.model.purchase_detail = this.model.purchase_detail.filter(item => item.seller_sku !== row.seller_sku)
                   })
                   this.multipleSelection = []
                    this.msgSuccess('删除成功')
                })
                .catch(() => {})
        },

        // 删除按钮操作
        handleDelete(row) {
            this.$confirm('是否确认删除?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.model.purchase_detail = this.model.purchase_detail.filter(item => item.seller_sku !== row.seller_sku)
                    this.msgSuccess('删除成功')
                })
                .catch(() => {})
        },
        showSellerDialog() {
            this.sellerDialog.visible = true
        },
        selectSeller(item) {
            this.addItem(item)
        },
        addSeller() {
            if (!this.model.seller_sku) {
                return
            }
            geWarehouseSku({ seller_sku: this.model.seller_sku }).then(res => {
                res.data.list.map(item => {
                    this.addItem(item)
                })
            })
        },
        addItem(item) {
            item.purchase_quantity =  item.in_stores_quantity || item.purchase_quantity || 1
            const index = this.model.purchase_detail.findIndex(i => i.seller_sku === item.seller_sku)
            if (index !== -1) {
                const temp = this.model.purchase_detail.find(i => i.seller_sku === item.seller_sku)
                temp.purchase_quantity = parseInt(temp.purchase_quantity) + parseInt(item.purchase_quantity)
                temp.purchase_cost = parseFloat(temp.purchase_price) * parseInt(temp.purchase_quantity).toFixed(2)
                this.model.purchase_detail.splice(index, 1, temp)
            } else {
                this.model.purchase_detail.push(item)
            }
        },
        chooseColor(item) {
            this.model.remark_color = item.value
        },
        getDetail() {
            this.loading = true
            const params = { purchase_number: this.model.purchase_number }
            getPurchaseDown(params)
                .then(res => {
                    this.model = Object.assign({}, this.model, res.data)
                })
                .finally(() => {
                    this.loading = false
                })
        },
        submit(type) {
            this.$refs.form.validate(valid => {
                if (!valid) {
                    return
                }
                const params = { ...this.model }
                if (type === 'save') {
                    delete params.is_pass
                    delete params.is_send
                } else if (type === 'send') {
                    params.is_send = 1
                    delete params.is_pass
                } else if (type === 'pass') {
                    params.is_pass = 1
                    delete params.is_send
                }
                if (this.save) {
                    return
                }
                this.save = true
                const requestMap = {
                    add: addPurchaseDown,
                    edit: editPurchaseDown,
                }
                requestMap[this.type](params)
                    .then(res => {
                        this.$message.success(res.msg)
                        this.dialogVisible = false
                        this.$emit('success')
                    })
                    .finally(() => {
                        this.save = false
                    })
            })
        },
        cancel() {
            this.dialogVisible = false
        },
    },
}
</script>

<style scoped>
.purchase-detail {
    position: relative;
    padding-bottom: 80px;
    min-height: calc(100vh - 100px);
}
.purchase-footer {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    text-align: right;
    padding: 20px;
}
.form-wrap-class.el-form .el-form-item {
    width: 50%;
    margin-right: 0;
}
/* .form-wrap-class.el-form .el-form-item .el-input {
    width: 250px;
} */
/* .form-wrap-class.el-form .el-form-item .el-textarea {
    width: 770px;
} */
.form-wrap-class.el-form .el-form-item .el-input-number,
.form-wrap-class.el-form .el-form-item .el-input-number .el-input {
    width: 120px;
}
.form-wrap-class.el-form .el-form-item .el-input-number + .el-input-number {
    margin-left: 10px;
}
.form-wrap-class.el-form .el-form-item.full {
    width: 100%;
}
.upload {
}
.upload-tip span {
    color: #ff4949;
    padding: 0 4px;
}
.color-list {
    display: flex;
    align-items: center;
    height: 36px;
}
.color-item {
    min-width: 20px;
    width: 20px;
    height: 20px;
    margin-right: 10px;
    cursor: pointer;
    white-space: nowrap;
    border-color: transparent;
}
</style>
